package xyz.matrix.web;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.cj.util.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import xyz.matrix.dao.GradeDao;
import xyz.matrix.model.Grade;
import xyz.matrix.model.PageBean;
import xyz.matrix.util.DbUtil;
import xyz.matrix.util.JsonUtil;
import xyz.matrix.util.ResponseUtil;

public class GradeListServlet extends HttpServlet{

	GradeDao gradeDao = new GradeDao();
	DbUtil dbUtil = new DbUtil();
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String page = request.getParameter("page");
		String rows = request.getParameter("rows");
		String gradeName = request.getParameter("gradeName");
		PageBean pageBean = new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
		if (StringUtils.isNullOrEmpty(gradeName)) {
			gradeName = "";
		}
		Grade grade = new Grade();
		grade.setGradeName(gradeName);
		Connection con = null;
		try {
			con = dbUtil.getCon();
			JSONObject result = new JSONObject();
			JSONArray jsonArray = JsonUtil.formatRsToJsonArray(gradeDao.gradeList(con, pageBean, grade));
			int total = gradeDao.gradeCount(con,grade);
			result.put("rows", jsonArray);
			result.put("total", total);
			ResponseUtil.write(response, result);
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			try {
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	
}
